import * as Types from 'containers/ActionTypes';
import * as Helper from 'Helper';
import * as MyWorkService from 'services/MyWorkService';

export function changeWorkStatus(workId, status) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }

    return MyWorkService.changeMyWork(accessToken, workId, status)
      .then((data) => {
        if (status === 'PUBLIC') {
          dispatch({ type: Types.MY.PUBLISH_SUCCESS });
        }
        if (status === 'PRIVATE') {
          dispatch({ type: Types.MY.UNPUBLISH_SUCCESS });
        }
        return data;
      });
  };
}

export function updateWorkDetail(workId, name, title, categoryId, description) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }

    return MyWorkService.updateMyWork(accessToken, workId, name, title, categoryId, description);
  };
}

export function deleteWork(workId, status) {
  return (dispatch, getState) => {
    const state = getState();
    const accessToken = Helper.getMyToken(state);

    if (!accessToken) {
      return Promise.reject('Unauthenticated');
    }

    return MyWorkService.deleteMyWork(accessToken, workId).then((data) => {
      dispatch({
        type: Types.MY.DELETE_SUCCESS, status,
      });
      // TODO dispatch unlike action
      return data;
    });
  };
}
